#include "contentitemoperation.h"

ContentItemOperation::ContentItemOperation(QObject *parent)
	: QObject(parent)
{}

ContentItemOperation& ContentItemOperation::getInstance()
{
	static ContentItemOperation oper;
	return oper;
}

void ContentItemOperation::selectAllContentItem()
{
	auto& conn = SqlConnection::getInstance();
	auto func = static_cast<SqlConnection::SelectCallBackFunc<ContentItem>>([](ContentItem& item,QSqlRecord& record) {
		int id = record.value("content_id").toInt();
		int nodeId = record.value("content_nodeid").toInt();
		int type = record.value("content_type").toInt();
		QString text = record.value("content_text").toString();
		int sort = record.value("content_sort").toInt();
		int finished = record.value("content_isfinished").toInt();
		item.init(id, nodeId, type, sort, finished, text);
		});
	std::list<ContentItem*> itemList = conn.selectAllFromTable<ContentItem>("todo_content", func);
	for (ContentItem* itemPtr : itemList) {
		m_itemMap[itemPtr->getNodeId()].push_back(itemPtr);
	}
}

std::list<ContentItem*> ContentItemOperation::getContentItemsByNodeId(int nodeId)
{
	if (m_itemMap.count(nodeId) == 0) {
		return std::list<ContentItem*>();
	}
	auto& itemList = m_itemMap[nodeId];
	itemList.sort([](const ContentItem* item1, const ContentItem* item2) {return item1->getSort() < item2->getSort(); });
	return itemList;
}

ContentItemOperation::~ContentItemOperation()
{}
